<?php
/**
 * +----------------------------------------------------------------------+
 * php23种设计模式实现-观察者模式
 * Author：微信公众号：yuantanphp
 * 获取更多资源，技术答疑，项目合作请关注微信公众号：yuantanphp
 * +----------------------------------------------------------------------+
 */
namespace Observer;
interface Observer
{
    public function beginWork($subject): void;
}
/**财务 */
class Finance implements Observer{
    function beginWork($subject):void{
        echo "财务部得到收款 {$subject->price} 并开出发票";
    }
}
/**行政 */
class Administration implements Observer{
    function beginWork($subject):void{
        echo "行政部开始统计销售信息<br>
        客户：{$subject->customer}<br>
        手机号：{$subject->customerMobile}<br>
        摩托车型号：{$subject->motorModel}<br>
        摩托车编号：{$subject->motorNo}<br>
        购买时间：{$subject->buyDateTime}<br>
        ";
    }
}
/**仓库 */
class Warehouse implements Observer{
    function beginWork($subject):void{
        echo "仓库接到通知并安排出库以及物流。出库信息及物流信息如下<br>
        客户：{$subject->customer}<br>
        手机号：{$subject->customerMobile}<br>
        摩托车型号：{$subject->motorModel}<br>
        摩托车编号：{$subject->motorNo}<br>";
    }
}
/**售后 */
class  AfterSale implements Observer{
    function beginWork($subject):void{
        echo "售后得到通知并带着客户{$subject->customer}去车管所上牌";
    }
}
class Order
{
    private $observers = [];
    public function attach($ob)
    {
        $this->observers[] = $ob;
    }

    public function detach($ob)
    {
        $position = 0;
        foreach ($this->observers as $observer) {
            if ($ob == $observer) {
                array_splice($this->observers, ($position), 1);
            }
            ++$position;
        }
    }
    public function notify($obj)
    {
        foreach ($this->observers as $ob) {
            $ob->beginWork($obj);
        }
    }
    public function sale()
    {
        $obj = new \stdClass();
        //客户
        $obj->customer = "叶先生";
        //购买时间
        $obj->buyDateTime = date("Y-m-d H:i:s");
        //摩托型号
        $obj->motorModel = "踏板摩托-上天";
        //客户手机号
        $obj->customerMobile = '13999999999';
        //摩托车编号
        $obj->motorNo = "123001";
        //销售价格
        $obj->price = 100000.00;
        $this->notify($obj);
    }
}
$finance = new Finance;
$administration = new Administration;
$warehouse = new Warehouse;
$afterSale = new AfterSale;
$order = new Order;
$order->attach($finance);
$order->attach($administration);
$order->attach($warehouse);
$order->attach($afterSale);
//销售出去了
$order->sale();